/* eslint-disable */

/**
 * list -> tree 转换工具
 *
 * 通过 compare()/setter() 回调的方式实现
 *
 * 这个工具的好处，就是直接使用原始数据进行组合，缺点就是，通过接口回调的方式实现，代码格式难看些。
 *
 * @constructor
 */
class TreeBuilder {
    constructor() {
        /**
         * 子级节点
         * @type {[any]}
         */
        this.child = undefined;
        /**
         * 父级节点
         * @type {[any]}
         */
        this.parent = undefined;

        /**
         * 比较大小
         * @type {Function}
         */
        this.compare = undefined;
        /**
         * 将子节点添加到父节点
         * @type {Function}
         */
        this.addChildNode = undefined
    }


    /**
     * 设置子级列表
     *
     * @param children {[any]}
     * @returns {TreeBuilder}
     */
    setChildren(children) {
        this.children = children;
        return this;
    }

    /**
     * 设置父级列表
     *
     * @param p {[any]} parent-list
     * @return this
     */
    setParent(p) {
        this.parent = p;
        return this;
    }


    /**
     * 获取父节点
     *
     * @returns {[]}
     */
    getParent() {
        return this.parent;
    }

    /**
     * 设置比较函数
     *
     * @param call {Function}
     * @returns {TreeBuilder}
     */
    setCompare(call) {
        this.compare = call;
        return this;
    }

    /**
     * 设置setter函数
     *
     * @param call {Function}
     * @returns {TreeBuilder}
     */
    setChildSetter(call) {
        this.addChildNode = call;
        return this;
    }

    /**
     * 数据分组
     *
     * @return {TreeBuilder}
     */
    groupBy() {
        if (this.parent === undefined && this.child === undefined) {
            throw new IllegalArgumentException("Child list and parent list are both empty!");
        }
        if (this.parent === undefined) {
            this.parent = this.child;
        }
        if (this.child === undefined) {
            this.child = this.parent;
        }

        for (let i = 0; i < this.parent.length; i++) {
            for (let j = 0; j < this.child.length; j++) {
                let p = this.parent[i], c = this.child[j];
                if (this.compare(p, c) === 0) {
                    this.addChildNode(p, c);
                }
            }
        }
        return this;
    }
}

export default TreeBuilder;
